package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/conquer/entity"
	"kop/util/rand"
)

func GetPointsByRoleID(dB *gorm.DB, roleID int32) (int32, bool) {

	var data = entity.ConquerPoints{
		RoleID: roleID,
	}
	if err := dB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, false
		} else {
			panic(err)
		}

	}

	return data.Points, true
}

func GetPoints(dB *gorm.DB, roleID int32) int32 {

	var data = entity.ConquerPoints{
		RoleID: roleID,
	}
	if err := dB.First(&data).Error; err != nil {
		panic(err)
	}

	return data.Points
}

func GetPoints200(dB *gorm.DB, serverID int32) []entity.ConquerPoints {

	var data []entity.ConquerPoints
	if err := dB.Where(entity.ConquerPoints{ServerID: serverID}).Order("points DESC").Limit(200).Find(&data).Error; err != nil {
		panic(err)
	}

	return data
}

const DefaultPoints = 1000

func CreatePoints(dB *gorm.DB, roleID, serverID int32) error {

	return dB.Create(&entity.ConquerPoints{RoleID: roleID, ServerID: serverID, Points: DefaultPoints}).Error
}

func AddPoints(dB *gorm.DB, roleID, points int32) error {

	return dB.Table("conquer_points").Where("role_id = ?", roleID).UpdateColumn("points", gorm.Expr("points + ?", points)).Error
}

func SubPoints(dB *gorm.DB, roleID, points int32) error {

	return dB.Table("conquer_points").Where("role_id = ?", roleID).UpdateColumn("points", gorm.Expr("points - ?", points)).Error
}

// 随机1个对手
// except 排除已随过的玩家
func RandOther(dB *gorm.DB, roleID, serverID int32, except []int32) (entity.ConquerPoints, bool) {

	var myPoints = entity.ConquerPoints{RoleID: roleID}
	if err := dB.First(&myPoints).Error; err != nil {
		panic(err)
	}

	except = append(except, roleID)
	var session = dB.Where(entity.ConquerPoints{ServerID: serverID}).Where("role_id NOT IN (?)", except)

	var data1 []entity.ConquerPoints
	if err := session.Where("points >= ?", myPoints.Points).Order("points ASC").Limit(20).Find(&data1).Error; err != nil {
		panic(err)
	}

	var data2 []entity.ConquerPoints
	if err := session.Where("points <= ?", myPoints.Points).Order("points DESC").Limit(20).Find(&data2).Error; err != nil {
		panic(err)
	}

	data1 = append(data1, data2...)

	if len(data1) == 0 {
		return entity.ConquerPoints{}, false
	} else {
		return data1[rand.Int(0, len(data1)-1)], true
	}
}
